<?php
namespace app\index\controller;

use think\Controller;
use think\Request;

class Upload extends Controller
{
    /**
     * KindEditor 文件上传接口
     * @return \think\response\Json
     */
    public function kindeditor()
    {
        // 允许的扩展名
        $ext_arr = [
            'image' => ['gif', 'jpg', 'jpeg', 'png', 'bmp'],
            'media' => ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm'],
            'file'  => ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'zip', 'rar', 'pdf']
        ];

        // 目录名参数 (默认 image)
        $dir = input('get.dir/s', 'image');
        if (!isset($ext_arr[$dir])) {
            return json(['error' => 1, 'message' => '目录名不正确。']);
        }

        // 获取上传文件 (KindEditor 默认字段名是 imgFile)
        $file = request()->file('imgFile');
        if (!$file) {
            return json(['error' => 1, 'message' => '没有选择文件。']);
        }

        // 设置保存路径
        $upload_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . $dir . DS . date('Ymd') . DS;
        if (!is_dir($upload_path)) {
            mkdir($upload_path, 0755, true);
        }

        // 验证扩展名并保存
        $info = $file->validate(['ext' => implode(',', $ext_arr[$dir])])
            ->move($upload_path);

        if ($info) {
            // 生成访问 URL
            $url = '/uploads/' . $dir . '/' . date('Ymd') . '/' . $info->getFilename();
            return json(['error' => 0, 'url' => $url]);
        } else {
            return json(['error' => 1, 'message' => $file->getError()]);
        }
    }
}
